<template>
  <el-dialog
    v-model="dialogVisible"
    title="切换供应商"
    width="400px"
    @close="resetForm"
  >
    <el-form ref="serviceForm" :model="form" :rules="rules">
      <el-form-item label="API提供商" prop="provider">
        <el-select
          v-model="form.provider"
          filterable
          clearable
          placeholder="请选择API提供商"
        >
          <el-option
            v-for="item in providerOptions"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleConfirm"
        >确定</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import { updateServiceProvider } from "@/api/adminServiceTypeApi";
import { message } from "@/utils/message";

const dialogVisible = ref(false);
defineProps({
  providerOptions: {
    type: Array,
    default: () => []
  }
});
const emits = defineEmits(["refresh"]);
const form = ref({
  code: "",
  provider: ""
});

// 基础校验规则
const rules = {
  provider: [{ required: true, message: "请选择API提供商", trigger: "change" }]
};

const serviceForm = ref(null);
// 重置表单
const resetForm = () => {
  serviceForm.value?.resetFields();
};
const submitLoading = ref(false);
const handleConfirm = () => {
  serviceForm.value.validate(async valid => {
    if (valid) {
      try {
        submitLoading.value = true;
        const { code, ...params } = form.value;
        await updateServiceProvider(code, params);
        message("切换成功", { type: "success" });
        emits("refresh");
        dialogVisible.value = false;
      } finally {
        submitLoading.value = false;
      }
    }
  });
};
const open = standardCode => {
  form.value.code = standardCode;
  dialogVisible.value = true;
};
defineExpose({
  open
});
</script>
